<script setup>
import Toast from '@vant/weapp/dist/toast/toast';

import inviteBgc from "@/assets/imgs/pages/invite/inviteBgc.png";
import people from "@/assets/imgs/pages/invite/people.png";
import chatBox from "@/assets/imgs/pages/invite/box.png";

import { getUnlimitedQRCode } from "@/api/register";
import { useUserStore } from "@/store/modules";
import { onMounted, ref, getCurrentInstance, nextTick, watch } from "vue";
import myCanvas from "@/utils/myCanvas.js";



const props = defineProps({
    show: {
        type: Boolean,
        default: false
    },
})

const emit = defineEmits(['update:show'])


const instance = getCurrentInstance()

const userStore = useUserStore()

const queryParams = ref({
    codeUrl: '',
    imageFileUrl: ''
})

const canvasDom = ref({})

let imgCanvas

const popupShow = ref(false)


watch(() => props.show, (val) => {
    if (val) {
        nextTick(() => {
            popupShow.value = true
        })
    }
})

// 保存图片
function saveImage() {
    uni.saveImageToPhotosAlbum({
        filePath: queryParams.value.imageFileUrl,
        success() {
            Toast.success('保存成功')
        }
    })
}


// 预览图片
function previewImage() {
    uni.previewImage({
        urls: [queryParams.value.imageFileUrl],
        current: queryParams.value.imageFileUrl,
    })
}


// 导出canvas图片
function exportCanvasImage() {
    return new Promise(resolve => {
        uni.canvasToTempFilePath({
            canvas: imgCanvas.canvas,
            x: 0,
            y: 0,
            success(res) {
                queryParams.value.imageFileUrl = res.tempFilePath
                resolve()
            },
        })
    })
}


// 关闭事件
function close() {
    emit('update:show', false)
    popupShow.value = false
}


// 绘图
function drawImageFn() {
    // 绘制背景图
    imgCanvas.drawRect(
        0,
        0,
        canvasDom.value.width,
        canvasDom.value.height,
        '#292650'
    )
    imgCanvas.drawImage(
        inviteBgc,
        0,
        0,
        canvasDom.value.width,
        canvasDom.value.height,
        undefined,
        async () => {

            imgCanvas.ctx.save()
            imgCanvas.drawRoundedRect(
                canvasDom.value.width / 2,
                100,
                100,
                50,
                'rgba(0, 0, 0, 0)',
            )
            imgCanvas.ctx.clip()
            await new Promise(resolve => {
                imgCanvas.drawImage(
                    userStore.userInfo.avatarUrl,
                    canvasDom.value.width / 2 - 50,
                    50,
                    100,
                    100,
                    undefined,
                    () => {
                        imgCanvas.ctx.restore()
                        imgCanvas.drawImage(people, 200, 140, 180, 180, undefined, () => {
                            imgCanvas.drawImage(chatBox, 20, 200, 172, 68, undefined, () => {
                                imgCanvas.drawText('图文带货助手', 35, 238, {
                                    color: '#fff',
                                    fontSize: 24,
                                })
                                imgCanvas.drawText('文案生成绘图创作一应俱全，', 35, 350, {
                                    color: '#fff',
                                    fontSize: 24,
                                })
                                imgCanvas.drawText('大大提高爆单机率。', 35, 400, {
                                    color: '#fff',
                                    fontSize: 24,
                                })
                                resolve()
                            })
                        })

                    }
                )
            })

            imgCanvas.ctx.save()
            imgCanvas.drawRoundedRectangle(
                canvasDom.value.width / 2 - 75,
                450,
                150,
                150,
                10,
                '#FFF'
            )
            imgCanvas.ctx.clip()
            await new Promise(resolve => {
                imgCanvas.drawImage(
                    queryParams.value.codeUrl,
                    canvasDom.value.width / 2 - 75,
                    450,
                    150,
                    150,
                    undefined,
                    () => {
                        imgCanvas.ctx.restore()
                        exportCanvasImage()
                        resolve()
                    }
                )
            })
        }
    )
}

// 获取小程序邀请二维码
async function getUnlimitedQRCodeFn() {
    const res = await getUnlimitedQRCode()
    queryParams.value.codeUrl = "data:image/png;base64," + wx.arrayBufferToBase64(res.data);
}

onMounted(async () => {
    await getUnlimitedQRCodeFn()
    nextTick(() => {
        uni.createSelectorQuery().in(instance).select('.imgCanvas').boundingClientRect((res) => {
            canvasDom.value = res
            imgCanvas = new myCanvas('imgCanvas', instance)
            setTimeout(() => {
                drawImageFn()
            }, 300)
        }).exec()
    })
})

const customStyle = `background-color:transparent !important;`
</script>

<template>
    <div class='inviteImg'>
        <canvas type="2d" id="imgCanvas" class="imgCanvas"></canvas>
    </div>
    <van-popup :show="popupShow" @close="close" :custom-style="customStyle">
        <div class="img_box" @click="previewImage">
            <img :src="queryParams.imageFileUrl" class="imgSty" mode="aspectFill" alt="">
        </div>
        <div class="download_btn" @click="saveImage">保存图片</div>
    </van-popup>
</template>

<style lang='scss' scoped>
.inviteImg {
    .imgCanvas {
        position: fixed;
        top: 0;
        left: 100%;
        width: 100%;
        height: 80vh;
    }

}

.img_box {
    .imgSty {
        width: 500rpx;
        height: 800rpx;
        border-radius: 30rpx;
    }

}

.download_btn {
    margin: 30rpx auto 0;
    width: 250rpx;
    height: 60rpx;

    font-size: 26rpx;
    color: var(--a-one-text-color);
    letter-spacing: 4rpx;
    border-radius: 50rpx;
    background-color: var(--a-main-color);

    display: flex;
    align-items: center;
    justify-content: center;
}
</style>